import React, { forwardRef, useImperativeHandle, useState } from 'react';
import { Form, Input, Modal, message, Spin } from 'antd';
import { updatePwd } from '@/services/system/user';

// 定义传参
interface UpdatePwdParams {}

/**
 * 修改密码
 *
 * @author zhangby
 * @date 29/9/20 4:34 pm
 */
const UpdatePwd: React.FC<UpdatePwdParams> = (props, ref) => {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  const [form] = Form.useForm();

  useImperativeHandle(ref, () => ({
    // 暴露给父组件的方法
    onPreInit: async () => {
      setVisible(true);
      form.resetFields();
    },
  }));

  // 提交
  const onSubmit = () => {
    form.validateFields().then(async (values) => {
      try {
        setLoading(true);
        const data = await updatePwd(values);
        if (data.code === '000') {
          message.success('修改密码成功');
          setVisible(false);
        }
        setLoading(false);
      } catch (e) {
        setLoading(false);
      }
    });
  };

  return (
    <>
      <Modal
        title="修改密码"
        visible={visible}
        onOk={onSubmit}
        onCancel={() => setVisible(false)}
        width={600}
      >
        <Spin spinning={loading}>
          <Form {...layout} form={form}>
            <Form.Item
              name="oldPwd"
              label="旧密码"
              rules={[
                {
                  required: true,
                  message: '请输入旧密码',
                },
              ]}
              hasFeedback
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="newPwd"
              label="密码"
              rules={[
                {
                  required: true,
                  message: '请输入密码',
                },
              ]}
              hasFeedback
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="confirm"
              label="确认密码"
              dependencies={['newPwd']}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: '请输入确认密码',
                },
                ({ getFieldValue }) => ({
                  validator(rule, value) {
                    if (!value || getFieldValue('newPwd') === value) {
                      return Promise.resolve();
                    }
                    // eslint-disable-next-line prefer-promise-reject-errors
                    return Promise.reject('密码与确认密码不正确');
                  },
                }),
              ]}
            >
              <Input.Password />
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
    </>
  );
};

const layout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 7 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
  },
};

// @ts-ignore
export default forwardRef(UpdatePwd);
